/* 用户认证管理 */
class AuthManager {
    constructor() {
        this.currentUser = null;
        this.isLoggedIn = false;
        this.userType = null;
        this.init();
    }

    init() {
        // 检查本地存储的登录状态
        this.checkAuthStatus();
        this.bindEvents();
    }

    // 确保认证模态框存在（部分页面未内置该HTML）
    ensureAuthModal() {
        if (document.getElementById('authModal')) return;
        const wrapper = document.createElement('div');
        wrapper.innerHTML = `
            <div class="modal" id="authModal" style="display:none;">
                <div class="modal-content">
                    <div class="modal-header">
                        <h2 id="modalTitle">用户登录</h2>
                        <span class="close" id="closeModal">&times;</span>
                    </div>
                    <div class="modal-body">
                        <form id="authForm">
                            <div class="form-group">
                                <label for="username">用户名</label>
                                <input type="text" id="username" name="username" required>
                            </div>
                            <div class="form-group">
                                <label for="password">密码</label>
                                <input type="password" id="password" name="password" required>
                            </div>
                            <div class="form-group" id="emailGroup" style="display: none;">
                                <label for="email">邮箱</label>
                                <input type="email" id="email" name="email">
                            </div>
                            <div class="form-group" id="phoneGroup" style="display: none;">
                                <label for="phone">手机号</label>
                                <input type="tel" id="phone" name="phone">
                            </div>
                            <div class="form-group" id="shopNameGroup" style="display: none;">
                                <label for="shopName">店铺名称</label>
                                <input type="text" id="shopName" name="shopName">
                            </div>
                            <div class="form-group" id="userTypeGroup" style="display: none;">
                                <label for="userType">用户类型</label>
                                <select id="userType" name="userType">
                                    <option value="Customer">买家</option>
                                    <option value="Seller">卖家</option>
                                </select>
                            </div>
                            <button type="submit" class="btn btn-primary" id="submitBtn">登录</button>
                        </form>
                        <div class="auth-switch">
                            <p id="switchText">还没有账号？<a href="#" id="switchLink">立即注册</a></p>
                        </div>
                    </div>
                </div>
            </div>`;
        document.body.appendChild(wrapper.firstElementChild);
    }

    bindEvents() {
        // 绑定登录/注册相关事件
        const userBtn = document.getElementById('userBtn');
        if (userBtn) userBtn.addEventListener('click', this.toggleUserDropdown.bind(this));
        const loginLink = document.getElementById('loginLink');
        if (loginLink) loginLink.addEventListener('click', this.showLoginModal.bind(this));
        const registerLink = document.getElementById('registerLink');
        if (registerLink) registerLink.addEventListener('click', this.showRegisterModal.bind(this));
        const logoutLink = document.getElementById('logoutLink');
        if (logoutLink) logoutLink.addEventListener('click', this.logout.bind(this));
        
        // 我的订单链接点击事件
        const ordersLink = document.getElementById('ordersLink');
        if (ordersLink) ordersLink.addEventListener('click', this.goToOrders.bind(this));
        
        // 绑定模态框事件
        const closeModal = document.getElementById('closeModal');
        if (closeModal) closeModal.addEventListener('click', this.hideAuthModal.bind(this));
        const authForm = document.getElementById('authForm');
        if (authForm) authForm.addEventListener('submit', this.handleAuthSubmit.bind(this));
        const switchLink = document.getElementById('switchLink');
        if (switchLink) switchLink.addEventListener('click', this.switchAuthMode.bind(this));
        
        // 点击模态框外部关闭
        const authModal = document.getElementById('authModal');
        if (authModal) {
            authModal.addEventListener('click', (e) => {
                if (e.target.id === 'authModal') {
                    this.hideAuthModal();
                }
            });
        }
    }

    checkAuthStatus() {
        const token = localStorage.getItem('authToken');
        const userData = localStorage.getItem('userData');
        const currentUser = localStorage.getItem('currentUser');
        
        // 优先检查currentUser，如果没有则检查userData
        let userInfo = null;
        if (currentUser) {
            try {
                userInfo = JSON.parse(currentUser);
            } catch (error) {
                console.error('解析currentUser失败:', error);
            }
        } else if (token && userData) {
            try {
                userInfo = JSON.parse(userData);
            } catch (error) {
                console.error('解析userData失败:', error);
            }
        }
        
        if (userInfo) {
            this.currentUser = userInfo;
            this.isLoggedIn = true;
            this.userType = userInfo.user_type || userInfo.userType;
            this.updateUI();
        }
    }

    updateUI() {
        const userName = document.getElementById('userName');
        const userDropdown = document.getElementById('userDropdown');
        const loginLink = document.getElementById('loginLink');
        const registerLink = document.getElementById('registerLink');
        const profileLink = document.getElementById('profileLink');
        const ordersLink = document.getElementById('ordersLink');
        const logoutLink = document.getElementById('logoutLink');
        const sellerLink = document.getElementById('sellerLink');

        if (this.isLoggedIn) {
            userName.textContent = this.currentUser.username;
            loginLink.style.display = 'none';
            registerLink.style.display = 'none';
            profileLink.style.display = 'block';
            ordersLink.style.display = 'block';
            logoutLink.style.display = 'block';
            
            // 如果是卖家，显示卖家中心链接
            if (this.userType === 'Seller') {
                sellerLink.style.display = 'block';
            }
        } else {
            userName.textContent = '登录';
            loginLink.style.display = 'block';
            registerLink.style.display = 'block';
            profileLink.style.display = 'none';
            ordersLink.style.display = 'none';
            logoutLink.style.display = 'none';
            sellerLink.style.display = 'none';
        }
    }

    toggleUserDropdown() {
        const dropdown = document.getElementById('userDropdown');
        dropdown.style.display = dropdown.style.display === 'block' ? 'none' : 'block';
    }

    showLoginModal() {
        this.showAuthModal('login');
    }

    showRegisterModal() {
        this.showAuthModal('register');
    }

    showAuthModal(mode) {
        this.ensureAuthModal();
        const modal = document.getElementById('authModal');
        const modalTitle = document.getElementById('modalTitle');
        const submitBtn = document.getElementById('submitBtn');
        const switchText = document.getElementById('switchText');
        const switchLink = document.getElementById('switchLink');
        const emailGroup = document.getElementById('emailGroup');
        const phoneGroup = document.getElementById('phoneGroup');
        const shopNameGroup = document.getElementById('shopNameGroup');
        const userTypeGroup = document.getElementById('userTypeGroup');

        if (mode === 'login') {
            modalTitle.textContent = '用户登录';
            submitBtn.textContent = '登录';
            switchText.innerHTML = '还没有账号？<a href="#" id="switchLink">立即注册</a>';
            emailGroup.style.display = 'none';
            phoneGroup.style.display = 'none';
            shopNameGroup.style.display = 'none';
            userTypeGroup.style.display = 'none';
        } else {
            modalTitle.textContent = '用户注册';
            submitBtn.textContent = '注册';
            switchText.innerHTML = '已有账号？<a href="#" id="switchLink">立即登录</a>';
            emailGroup.style.display = 'block';
            phoneGroup.style.display = 'block';
            userTypeGroup.style.display = 'block';
            // 店铺名称字段默认隐藏，根据用户类型动态显示
            shopNameGroup.style.display = 'none';
        }

        modal.style.display = 'block';
        document.body.style.overflow = 'hidden';
        
        // 重新绑定切换链接事件
        const switchAnchor = document.getElementById('switchLink');
        if (switchAnchor) switchAnchor.addEventListener('click', this.switchAuthMode.bind(this));
        
        // 绑定用户类型切换事件
        const userTypeSelect = document.getElementById('userType');
        if (userTypeSelect) {
            userTypeSelect.addEventListener('change', this.handleUserTypeChange.bind(this));
        }
    }

    hideAuthModal() {
        const modal = document.getElementById('authModal');
        if (modal) {
            modal.style.display = 'none';
            document.body.style.overflow = 'auto';
        }
        const form = document.getElementById('authForm');
        if (form) form.reset();
    }

    handleUserTypeChange() {
        const userType = document.getElementById('userType').value;
        const shopNameGroup = document.getElementById('shopNameGroup');
        
        if (userType === 'Seller') {
            shopNameGroup.style.display = 'block';
        } else {
            shopNameGroup.style.display = 'none';
        }
    }

    switchAuthMode(e) {
        e.preventDefault();
        const currentMode = document.getElementById('modalTitle').textContent === '用户登录' ? 'login' : 'register';
        this.showAuthModal(currentMode === 'login' ? 'register' : 'login');
    }

    async handleAuthSubmit(e) {
        e.preventDefault();
        
        const formData = new FormData(e.target);
        const data = Object.fromEntries(formData);
        
        const submitBtn = document.getElementById('submitBtn');
        const originalText = submitBtn.textContent;
        
        try {
            submitBtn.textContent = '处理中...';
            submitBtn.disabled = true;

            let result;
            if (data.username && data.password && !data.email) {
                // 登录
                result = await api.login(data.username, data.password);
            } else {
                // 注册
                // 如果用户类型不是卖家，移除店铺名称字段
                if (data.userType !== 'Seller') {
                    delete data.shopName;
                }
                result = await api.register(data);
            }

            if (result.success) {
                this.handleAuthSuccess(result.data);
                this.hideAuthModal();
                this.showNotification('操作成功！', 'success');
            } else {
                this.showNotification(result.error || '操作失败', 'error');
            }
        } catch (error) {
            console.error('认证失败:', error);
            this.showNotification('网络错误，请稍后重试', 'error');
        } finally {
            submitBtn.textContent = originalText;
            submitBtn.disabled = false;
        }
    }

    handleAuthSuccess(userData) {
        // 保存用户数据和令牌
        localStorage.setItem('userData', JSON.stringify(userData));
        localStorage.setItem('authToken', userData.token || 'mock-token');
        localStorage.setItem('currentUser', JSON.stringify(userData));
        
        // 更新当前状态
        this.currentUser = userData;
        this.isLoggedIn = true;
        this.userType = userData.user_type;
        
        // 更新UI
        this.updateUI();
        
        // 通知购物车管理器用户已登录
        if (window.cartManager) {
            window.cartManager.onUserLogin();
        }
    }

    async logout() {
        try {
            await api.logout();
        } catch (error) {
            console.error('登出请求失败:', error);
        } finally {
            this.clearAuthData();
            this.showNotification('已退出登录', 'success');
        }
    }

    goToOrders() {
        // 检查用户是否已登录
        if (!this.isAuthenticated()) {
            this.showLoginModal();
            return;
        }
        
        // 跳转到订单页面
        window.location.href = 'orders.html';
    }

    clearAuthData() {
        localStorage.removeItem('authToken');
        localStorage.removeItem('userData');
        localStorage.removeItem('currentUser');
        this.currentUser = null;
        this.isLoggedIn = false;
        this.userType = null;
        this.updateUI();
        
        // 通知购物车管理器用户已登出
        if (window.cartManager) {
            window.cartManager.onUserLogout();
        }
    }

    showNotification(message, type = 'info') {
        const notification = document.getElementById('notification');
        const notificationText = document.getElementById('notificationText');
        
        notificationText.textContent = message;
        notification.className = `notification ${type}`;
        notification.classList.add('show');
        
        setTimeout(() => {
            notification.classList.remove('show');
        }, 3000);
    }

    // 检查用户权限
    hasPermission(requiredType) {
        if (!this.isLoggedIn) return false;
        if (requiredType === 'any') return true;
        return this.userType === requiredType;
    }

    // 获取当前用户信息
    getCurrentUser() {
        return this.currentUser;
    }

    // 检查是否已登录
    isAuthenticated() {
        return this.isLoggedIn;
    }
}

// 创建全局认证管理器实例
window.authManager = new AuthManager();
